package com.example.courseapp.activity;

import static com.example.courseapp.utils.BigDecimalUtils.toFixed;

import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.example.courseapp.R;
import com.example.courseapp.RetrofitHelper;
import com.example.courseapp.bean.ChartBean;
import com.example.courseapp.bean.ChildSportRecords;
import com.example.courseapp.net.CourseService;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.Utils;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ChartActivity extends AppCompatActivity implements OnChartGestureListener, OnChartValueSelectedListener {

    List<String> foodL = new ArrayList<>();

    LineChart mLineChar;

    CourseService service;
    Integer childID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_chart);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        findViewById(R.id.back).setOnClickListener(v -> {
            finish();
        });
        mLineChar = findViewById(R.id.mLineChar);

        service = RetrofitHelper.getInstance().createService(CourseService.class);
        childID = getIntent().getIntExtra("childID", 0);

        chartInit();

        service.getStatistics(childID).enqueue(new Callback<ChartBean>() {
            @Override
            public void onResponse(Call<ChartBean> call, Response<ChartBean> response) {
                ChartBean data = response.body();
                LogUtils.i("chart data == "+ GsonUtils.toJson(data));
                ArrayList<Entry> values = new ArrayList<Entry>();
                for (int i=0;i<data.getDataList().size();i++){
                    values.add(new Entry(i, Float.valueOf(data.getDataList().get(i))));
                }
                //设置数据
                setData(values,data.getTimeList());
            }

            @Override
            public void onFailure(Call<ChartBean> call, Throwable t) {
                LogUtils.e("Statistics error === "+t);
            }
        });


    }

    private void chartInit() {

        //设置手势滑动事件
        mLineChar.setOnChartGestureListener(this);
        //设置数值选择监听
        mLineChar.setOnChartValueSelectedListener(this);
        //后台绘制
        mLineChar.setDrawGridBackground(false);
        //设置描述文本
        mLineChar.getDescription().setEnabled(false);
        //设置支持触控手势
        mLineChar.setTouchEnabled(true);
        //设置缩放
        mLineChar.setDragEnabled(true);
        //设置推动
        mLineChar.setScaleEnabled(true);
        //如果禁用,扩展可以在x轴和y轴分别完成
        mLineChar.setPinchZoom(true);


        YAxis leftAxis = mLineChar.getAxisLeft();

        //y轴最大
        leftAxis.setAxisMaximum(5000f);
        //y轴最小
        leftAxis.setAxisMinimum(10f);
        leftAxis.enableGridDashedLine(10f, 10f, 0f);
        leftAxis.setDrawZeroLine(false);
        
        // 限制数据(而不是背后的线条勾勒出了上面)
//        leftAxis.setDrawLimitLinesBehindData(true);

        mLineChar.getAxisRight().setEnabled(false);


        //默认动画
        mLineChar.animateX(2500);
        //刷新
        //mChart.invalidate();

        // 得到这个文字
        Legend l = mLineChar.getLegend();

        // 修改文字 ...
        l.setForm(Legend.LegendForm.LINE);
    }
    LineDataSet set1;
    private void setData(ArrayList<Entry> values, List<String> timeList) {

        if (mLineChar.getData() != null && mLineChar.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) mLineChar.getData().getDataSetByIndex(0);
            set1.setValues(values);
            mLineChar.getData().notifyDataChanged();
            mLineChar.notifyDataSetChanged();
        } else {
            ValueFormatter valueFormatter =new ValueFormatter() {
                @Override
                public String getFormattedValue(float value) {
                    //对X轴上的值进行Format格式化，转成相应的值
                    int intValue = (int) value;
                    if (timeList.size() > intValue && intValue >= 0) {
                        return timeList.get(intValue).toString();
                    } else {
                        return "";
                    }
                }
            };
            mLineChar.getXAxis().setValueFormatter(valueFormatter);
            mLineChar.getXAxis().setLabelCount(timeList.size());
            // 创建一个数据集,并给它一个类型
            set1 = new LineDataSet(values, "近七天能量摄入的");

            // 在这里设置线
            set1.enableDashedLine(10f, 5f, 0f);
            set1.enableDashedHighlightLine(10f, 5f, 0f);
            set1.setColor(Color.BLACK);
            set1.setCircleColor(Color.BLACK);
            set1.setLineWidth(1f);
            set1.setCircleRadius(3f);
            set1.setDrawCircleHole(false);
            set1.setValueTextSize(9f);
            set1.setDrawFilled(true);
            set1.setFormLineWidth(1f);
//            set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
            set1.setFormSize(15.f);

            if (Utils.getSDKInt() >= 18) {
                // 填充背景只支持18以上
                //Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.ic_launcher);
                //set1.setFillDrawable(drawable);
                set1.setFillColor(Color.YELLOW);
            } else {
                set1.setFillColor(Color.BLACK);
            }
            ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
            //添加数据集
            dataSets.add(set1);

            //创建一个数据集的数据对象
            LineData data = new LineData(dataSets);
            //谁知数据
            mLineChar.setData(data);
        }
    }


    @Override
    public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {

    }

    @Override
    public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
// 完成之后停止晃动
        if (lastPerformedGesture != ChartTouchListener.ChartGesture.SINGLE_TAP)
            mLineChar.highlightValues(null);
    }

    @Override
    public void onChartLongPressed(MotionEvent me) {

    }

    @Override
    public void onChartDoubleTapped(MotionEvent me) {

    }

    @Override
    public void onChartSingleTapped(MotionEvent me) {

    }

    @Override
    public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {

    }

    @Override
    public void onChartScale(MotionEvent me, float scaleX, float scaleY) {

    }

    @Override
    public void onChartTranslate(MotionEvent me, float dX, float dY) {

    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }
}